package com.example.springtest.user.service.impl;


import com.example.springtest.common.ServiceCode;
import com.example.springtest.common.ServiceException;
import com.example.springtest.user.mapper.UserMapper;
import com.example.springtest.user.pojo.dto.UserDTO;
import com.example.springtest.user.pojo.entity.User;
import com.example.springtest.user.pojo.vo.UserVO;
import com.example.springtest.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    /**
     * 登录
     * @param
     * @return
     */
    @Override
public UserVO login(User user1){
    User user= userMapper.getUserByName(user1.getUsername());
    if(user==null){
        throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"用户不存在！");
    }
    String password=user1.getPassword();
    if(!password.equals(user.getPassword())){
        throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"密码不正确！");
    }
    UserVO userVO=new UserVO();
    userVO.setUsername(user.getUsername());
    userVO.setPassword(user.getPassword());
    return userVO;
}

    /**
     * 注册
     * @param userDTO
     * @return
     */
    @Override
public void register(UserDTO userDTO){
        User user=userMapper.getUserByName(userDTO.getUsername());
    if(user!=null){
        throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"用户已存在！");
    }
    if(!userDTO.getPassword().equals(userDTO.getRePassword())){
        throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"密码不一致！");
    }
    User user1=new User();
    user1.setUsername(userDTO.getUsername());
    user1.setPassword(userDTO.getPassword());
    userMapper.saveUser(user1);
}
@Override
  public User getUser(Integer id){
        User user=userMapper.getById(id);
if(user==null){
    throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"没有该用户！");
}

return user;
  }

  @Override
  public void deleteUser(Integer id){
      User user=userMapper.getById(id);
      if(user==null){
          throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"没有该用户！");
      }

      int result =userMapper.delete(id);
      if(result<=0){
          throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"删除失败！");
      }
  }

  public void editUser(Integer id,User user){
      User user1=userMapper.getById(id);
      if(user==null){
          throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"没有该用户！");
      }
     user1.setUsername(user.getUsername());
      user1.setPassword(user.getPassword());
      user1.setSchool(user.getSchool());
      user1.setMailbox(user.getMailbox());
      int result = userMapper.edit(user1);
      if(result<=0){
          throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"编辑失败！");
      }
  }
}
